package main

import (
	"fmt"
	"net/http"
	"strconv"

	"github.com/vmware-labs/wasm-workers-server/kits/go/worker"
)

func main() {
	worker.ServeFunc(func(w http.ResponseWriter, r *http.Request) {
		cache, _ := r.Context().Value(worker.CacheKey).(map[string]string)

		var countNum uint32

		if count, ok := cache["counter"]; ok {
			n, _ := strconv.ParseUint(count, 10, 32)
			countNum = uint32(n)
		}

		body := fmt.Sprintf("<!DOCTYPE html>"+
			"<body>"+
			"<h1>Key / Value store in Go</h1>"+
			"<p>Counter: %d</p>"+
			"<p>This page was generated by a Wasm module built from Go.</p>"+
			"</body>", countNum)

		cache["counter"] = fmt.Sprintf("%d", countNum+1)

		w.Header().Set("x-generated-by", "wasm-workers-server")
		w.Write([]byte(body))
	})
}
